<?php

/**
 * @author liyi
 * @copyright 2018 1.9
 */
namespace Pwtwogame\Controller;
use Common\Controller\ApiController;
use Think\Model;
use Think\Log;

class IndexController extends ApiController {

    //const QID_UID ='pwzw:qid:%s:type:%s'; // 用户分享到群限制

    const GAME_TYPE = 'Pwtwogame';  // 游戏类型

    const QID_UID ='pwzwtwo:user:%s:type:%s:qid:%s'; // 用户分享到群限制

    const PWZW_NAME = "pwzwtwos";  // 分享次数缓存键

    const PWZW_SHARE = "pwzwtwos:share";  // 分享次数缓存域

    const PWZW_PLAY = "pwzwtwos:play"; // 游戏次数

    const PWZW_AUTH_USER = "pwzwtwos:auth_user";  // 每日新增用户

    const PWZW_TOURIST = "pwzwtwos:tourist"; // 游戏游客用户

    const PWZW_INVITE = "pwzwtwos:invite"; // 邀请用户次数

    const PWZW_UPGRADE = "pwzwtwos:upgrade"; // 用户升级次数

    const PWZW_TEST = "pwzwtwotest:userid:%s"; // 用户升级次数

    const RANK_LIST = "pwzwtwo:rankList"; // 排汗榜列表(缓存)

    const USER_SHARE = 'pwzwtwonew:share:%s:type:%s';  // 点击分享按钮的次数

    const USER_VIDEO = 'pwzwtwonew:video:%s:type:%s';  // 看完视频的用户

    const DB_USER_NAME = "pwtwo_game.users"; // 游戏用户数据表

    const DB_INVITELOG_NAME = "pwtwo_game.users_invite"; // 游戏邀请数据表


    public function __construct()
    {
        parent::__construct();
        /*$uid = $this->isLogin(self::GAME_TYPE);
        $id = I('id','','int');

        if(empty($uid)) {
            $uid = $id;
            //$uid = $this->isParamLogin($id);
        }
        if (!$uid) {
            $this->response(1,'请先登录');
        }
        $this->uid = $uid;      // 用户登录id
        */
        $source = I('source','','int');  // 渠道来源
        $this->sid = $source;   // 渠道

    }

    // 排行榜
    public function rankingList()
    {
        $memory = memory_get_usage();
        $users = I('users','','string');
        $this->rules();
        $ret = array();
        $redis = REDIS('activity');
        $redis->select(2);
        $hash_key = self::RANK_LIST;    //排行榜缓存键

        $ret = $this->getRankList($hash_key,true,2,'s');
        if(empty($ret)) {
            //$where['nickname'] = array('neq','');
            //$where['avatar'] = array('neq','');
            $where['black_list'] = 1;
            $ret = M('users')->field('score as s,userid,nickname,avatar,id')->where($where)->order('s desc')->limit(200)->select();
            foreach($ret as $k=>$v) {
                if(!empty($v['nickname']) && !empty($v['avatar'])){
                    $id = $v['id'];
                    $flag = $redis->hSet($hash_key,$id, json_encode($v));
                }
            }
        }
        $memory2 = memory_get_usage();
        $jsons['errno'] = 0;
        $jsons['result'] = $ret;
        unset($ret);
        log::write("排行榜内存：".$this->convert($memory2-$memory));
        $this->ajaxReturn($jsons);
    }

    // 排行榜限制范文
    public function rules() {
        $redis = REDIS('activity');
        $redis->select(2);
        $ip = get_client_ip();
        $userKey = 'ipuser:%s:api_count';
        $key = sprintf($userKey,$ip);  //用户主键分享到群
        $check = $redis->exists($key);

        if($check){
            $redis->incr($key);  //键值递增
            $count = $redis->get($key);
            if($count > 2){
                $jsons['errno'] = 0;
                $jsons['result'] = array();
                $this->ajaxReturn($jsons);
                //exit('your have too many request');
            }
        }else{
            $redis->incr($key);
            //限制时间为60秒
            $redis->expire($key,1);
        }
    }

    // 游戏复活
    public function revives()
    {
        $uid = $this->uid;
        $revive = I('revive',0,'int'); // 复活金币

        $res = $this->revive($uid,$revive,3);
        if(!$res) {
            $this->response(1, "操作失败");
        }
        $this->response(0, "操作成功");
    }

    // 记录用户点击分享按钮的次数(外)
    public function setShare() {
        $userid = I('userid','','string'); // 用户userid
        $type = I('type',1,'int');  // 1:分享次数 2：分享完成(暂停) 3：看完视频次数 4：点击视频次数
        $redis = REDIS('activity');
        $userKey = sprintf(self::USER_SHARE,$userid,$type);  //用户主键分享到群

        $arr = array(1=>'shareNum',3=>'endvedio',4=>'vedioNum');
        $typeName = $arr[$type];

        $this->countLog('pwzwtwos','pwzwtwos:'.$typeName);  // 记录看完视频的次数

        $this->response(0,'ok');
    }

    // 记录用户点击分享按钮的次数(内)
    private function _setShare($userid,$type) {
        $redis = REDIS('activity');
        $redis->select(5);
        $userKey = sprintf(self::USER_SHARE,$userid,$type);  // 1:分享完成 2：已废弃 3：看完视频次数 4：钻石换金币次数
        if($type == 1 || $type == 3 || $type == 4) {
            $redis->incrBy($userKey,1);
            $redis->exprieAt($userKey,strtotime(date('Y-m-d 23:59:59'))); // 每日23点59分过期
        }
    }

    // 分享奖励
    public function shareAward()
    {
        $shareType = I('shareType',1,'intval'); // 1:分享完成 2：已废弃 3：看完视频次数 4：钻石换金币次数
        $userid = I('userid','','string'); // 用户userid
        $gold = I('gold',0,'string'); // 金币

        if(empty($userid)) {
            $jsons = array('errno'=>2,'msg'=>'用户不存在');
            $this->ajaxReturn($jsons);
        }

        if(empty($gold)){
            $jsons = array('errno'=>1,'msg'=>'金币不能为空');
            $this->ajaxReturn($jsons);
        }


        $map['userid'] = $userid;
        // 增加金币
        $ret = M('users')->where($map)->setInc('gold',$gold);

        // 分享记录
        $data['userid'] = $userid;
        $data['share_type'] = $shareType;
        $data['create_time'] = date('Y-m-d H:i:s');
        $ret2 = M('users_share_log')->add($data);

        $this->_setShare($userid,$shareType);// 分享数据插入缓存


        $jsons = array('errno'=>0,'msg'=>'分享成功');
        $this->ajaxReturn($jsons);

        // switch($shareType){
        //     case 1: // 首页分享

        //         break;

        //     case 3: // 视频分享
        //         $map['userid'] = $userid;
        //         // 增加金币
        //         $ret = M('users')->where($map)->setInc('gold',$gold);

        //         // 分享记录
        //         $data['userid'] = $userid;
        //         $data['share_type'] = $shareType;
        //         $data['create_time'] = date('Y-m-d H:i:s');
        //         $ret2 = M('users_share_log')->add($data);

        //         $this->setShare($userid,$shareType);
        //         $jsons = array('errno'=>0,'msg'=>'看完视频成功');
        //         $this->ajaxReturn($jsons);
        //         break;
        // }
    }

    // 获取用户信息
    public function getUserInfo(){
        $userid = I('userid','','string');
        if(!$userid){
            $jsons['errno'] = 1;
            $jsons['msg'] = '用户userid不能为空';
            $this->ajaxReturn($jsons);
        }

        $map['userid'] = $userid;
        $users = M('users')->where($map)->find();
        if($users){

            // 用户最优成绩
            //$ret = M('users_game_result')->where($map)->order('score desc')->find();
            $users['good_score'] = !empty($users['score']) ? $users['score'] : 0;

            $redis = REDIS('activity');
            $redis->select(5);

            $shareKey = sprintf(self::USER_SHARE,$userid,1);  //分享键
            $vedioKey = sprintf(self::USER_SHARE,$userid,3);  //视频键
            $goldKey = sprintf(self::USER_SHARE,$userid,4);  //钻石换金币次数

            $share = $redis->get($shareKey);
            $vedio = $redis->get($vedioKey);
            $gold = $redis->get($goldKey);

            $share_count = array(1=>intval($share), 3=>intval($vedio), 4=>intval($gold));

            $users['share_count'] = $share_count;
            //echo M()->getLastSql();

            $jsons['errno'] = 0;
            $jsons['result'] = $users;
        }else{
            $jsons['errno'] = 1;
            $jsons['msg'] = '用户不存在';
        }
        $jsons['serverTime'] = time();

        $this->ajaxReturn($jsons);
    }

    // 获取SessionKey
    public function getSessionKey()
    {
        $appId = C('APPID');
        $appSecret = C('APPSECRET');
        $code = I('code','','string');

        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appId&secret=$appSecret&js_code=$code&grant_type=authorization_code";
        $opts['http'] = array('method'=>'GET', 'timeout'=>5); // 设置超时5s
        $data = @file_get_contents($url, false, stream_context_create($opts));

        $data = $data ? @json_decode($data, true) : '';
        $jsons['errno'] = 0;
        $jsons['result'] = $data;
        $this->ajaxReturn($jsons);
    }

    // 解密数据
    public function cryptData()
    {
        $uid = $this->uid;
        $sessionKey = I('sessionKey','','string'); // sessionKey
        $encryptedData = I('encryptedData','','string'); // 加密数据
        $iv = I('iv','','string');
        $type = I('type',0,'int');  // 1:缓存当天有效 2：每局游戏有效

        $gameType = self::GAME_TYPE; // 游戏类型
        $cacheKey = self::QID_UID;   // 用户分享到群缓存键
        $cacheKey2 = self::PWZW_NAME; // 用户分享键
        $cacheval = self::PWZW_SHARE;  // 用户分享域

        $this->getCryptData($uid,$gameType,$type=1,$cacheKey,$sessionKey,$encryptedData,$iv,$cacheKey2,$cacheval);

    }

    // 获取用户邀请
    public function getUserInvite()
    {
        $userid = I('userid','','string');
        //$start_time = date('Y-m-d 00:00:00'); // 开始时间
        //$end_time = date('Y-m-d 23:59:59'); // 结束时间

        $map['userid'] = $userid;
        $map['type'] = array("neq",99);
        $map['left(create_time,10)'] = date('Y-m-d');
        $list = M('users_invite')->field('id,invited_userid,create_time')->where($map)->order('id asc')->select();
        if(empty($list)) {
            $jsons = array('errno'=>0,'result'=>"");
            $this->ajaxReturn($jsons);
        }

        $uidArr = array_column($list,'invited_userid');
        $timeArr = array_column($list,'create_time','invited_userid');
        $uidStr = implode(',', $uidArr);

        $where['userid'] = array('in',$uidStr);

        $str = null;
        foreach($uidArr as $k=>$v) {
            $str .= "'$v',";
        }
        $strs = rtrim($str,',');
        $userInfo = M('users')->field('id,userid,nickname,avatar')->where($where)->order('field(userid,'.$strs.')')->select();

        foreach($userInfo as $k=>$v) {
            $userInfo[$k]['create_time'] = $timeArr[$v['userid']];
        }

        // $map['I.userid'] = $userid;
        // $map['I.create_time'] = array('BETWEEN',array($start_time, $end_time));
        // $inviteList = M('users_invite')->alias('I')
        //     ->field('U.userid, U.nickname, U.avatar, I.create_time')
        //     ->join('INNER JOIN c_users U ON U.userid = I.invited_userid')
        //     ->where($map)
        //     ->select();

        $jsons['errno'] = 0;
        $jsons['result'] = $userInfo ? $userInfo : '';
        $this->ajaxReturn($jsons);
    }

    // 清理邀请记录
    public function removeRecord() {
        $userid = I('userid','','string');

        $date = date('Y-m-d');
        $map['userid'] = $userid;
        $map['left(create_time,10)'] = $date;
        $ret = M('users_invite')->where($map)->delete();

        if($ret) {
            $jsons['errno'] = 0;
            $jsons['msg'] = '操作成功';
            $this->ajaxReturn($jsons);
        }
        $jsons['errno'] = 1;
        $jsons['msg'] = '操作失败';
        $this->ajaxReturn($jsons);
    }


    // 邀请记录
    public function inviteRecord()
    {
        $userid = I('userid','','string');
        $invited_userid = I('invited_userid','','string');
        $start_time = date('Y-m-d 00:00:00'); // 开始时间
        $end_time = date('Y-m-d 23:59:59'); // 结束时间
        $type = I('type','','string');

        // 转发邀请记录
        $typeForward = array("101", "102", "103");
        if (in_array($type, $typeForward)) {
            $type_table = 'pwtwo';   // redis表
            $this->getForward($userid, $invited_userid, $type_table, $type);
        }

        $map['userid'] = $userid;
        $map['invited_userid'] = $invited_userid;
        $map['create_time'] = array('BETWEEN',array($start_time, $end_time));


        if(empty($invited_userid) || $invited_userid == 'undefined'){
            $jsons['errno'] = 1;
            $jsons['msg'] = '被邀请人userid不能为空';
            $this->ajaxReturn($jsons);
        }else if($userid == $invited_userid){
            $jsons['errno'] = 2;
            $jsons['msg'] = '不能邀请自己';
            $this->ajaxReturn($jsons);
        }else if($ret = M('users_invite')->where($map)->find()){
            $jsons['errno'] = 3;
            $jsons['msg'] = '已被邀请过';
            $this->ajaxReturn($jsons);
        }else{
            $data['userid'] = $userid;
            $data['invited_userid'] = $invited_userid;
            $data['create_time'] = date('Y-m-d H:i:s');
            $ret = M('users_invite')->add($data);
            log::write("inviteRecord:".$userid,"ERROR");
            if($ret){

                $this->countLog('pwzwtwos',self::PWZW_INVITE,1);  // 记录邀请次数

                $jsons['errno'] = 0;
                $jsons['msg'] = '邀请成功';
                $this->ajaxReturn($jsons);
            }else{
                $jsons['errno'] = 4;
                $jsons['msg'] = '邀请失败';
                $this->ajaxReturn($jsons);
            }
        }
    }

    // 邀请记录 (需增加type 无限钻石)
    public function inviteRecord2()
    {
        $userid = I('userid','','string');// openid
        $invited_userid = I('invited_userid','','string');
        $type = I('type','','string');
        $start_time = date('Y-m-d 00:00:00'); // 开始时间
        $end_time = date('Y-m-d 23:59:59'); // 结束时间

        $map['userid'] = $userid;
        $map['invited_userid'] = $invited_userid;
        $map['create_time'] = array('BETWEEN',array($start_time, $end_time));

        // 无限钻石
        if($type == '99'){
            // 判断被邀请人是否新老用户 老用户不能再次邀请 新用户每人只能被邀请一次
            $where['userid'] = $invited_userid;
            $where['type'] = 2;// 老用户标识
            $user_id = M('users')->where($where)->find();
            if( !empty($user_id)){
                $this->response(2, "只能邀请一次");
            }else{
                // 如果是新用户 增加邀请表 更新老用户标识
                $w_user['userid'] = $invited_userid;
                $w_data['type'] = 2;  //老用户
                $w_data['update_time'] = date('Y-m-d H:i:s');
                $ret2 = M('users')->where($w_user)->save($w_data);

                $data['userid'] = $userid;
                $data['invited_userid'] = $invited_userid;
                $data['create_time'] = date('Y-m-d H:i:s');
                $data['type'] = $type;
                $ret = M('users_invite')->add($data);
                if(empty($ret) && empty($ret2)) {
                    $this->response(1, "操作失败");
                }else{
                    $this->response(0, "操作成功");
                }
            }
        }

        if(empty($invited_userid) || $invited_userid == 'undefined'){
            $jsons['errno'] = 1;
            $jsons['msg'] = '被邀请人userid不能为空';
            $this->ajaxReturn($jsons);
        }else if($userid == $invited_userid){
            $jsons['errno'] = 2;
            $jsons['msg'] = '不能邀请自己';
            $this->ajaxReturn($jsons);
        }else if($ret = M('users_invite')->where($map)->find()){
            $jsons['errno'] = 3;
            $jsons['msg'] = '已被邀请过';
            $this->ajaxReturn($jsons);
        }else{
            $data['userid'] = $userid;
            $data['invited_userid'] = $invited_userid;
            $data['create_time'] = date('Y-m-d H:i:s');
            $ret = M('users_invite')->add($data);
            if($ret){

                $this->countLog('pwzwtwos',self::PWZW_INVITE,1);  // 记录邀请次数

                $jsons['errno'] = 0;
                $jsons['msg'] = '邀请成功';
                $this->ajaxReturn($jsons);
            }else{
                $jsons['errno'] = 4;
                $jsons['msg'] = '邀请失败';
                $this->ajaxReturn($jsons);
            }
        }
    }

    // 离线金币领取
    public function getGameGold()
    {
        $userid = I('userid','','string');
        $gold = I('gold',0,'string');

        $map['userid'] = $userid;
        $data['offline_time'] = 0;
        $data['gold'] = array('exp',"gold + $gold");
        $ret = M('users')->where($map)->save($data);
        if($ret){
            $jsons['errno'] = 0;
            $jsons['msg'] = '操作成功';
            $this->ajaxReturn($jsons);
        }else{
            $jsons['errno'] = 1;
            $jsons['msg'] = '操作失败';
            $this->ajaxReturn($jsons);
        }
    }


    // 设置金币
    public function set_Gold()
    {
        $userid = I('userid','','string'); // 用户userid
        $type = I('type','inc','string'); // 操作类型：inc增加，dec减少
        $gold = I('gold',0,'string'); // 金币

        $map['userid'] = $userid;

        if(!$userid){
            $jsons['errno'] = 1;
            $jsons['msg'] = '用户userid不能为空';
            $this->ajaxReturn($jsons);
        }else if(!$users = M('users')->where($map)->find()){
            $jsons['errno'] = 2;
            $jsons['msg'] = '用户不存在';
            $this->ajaxReturn($jsons);
        }else if($gold < 0){
            $jsons['errno'] = 3;
            $jsons['msg'] = '金币不能小于0';
            $this->ajaxReturn($jsons);
        }else if($type == 'dec' && $users['gold'] < $gold){
            $jsons['errno'] = 4;
            $jsons['msg'] = '金币不足';
            $this->ajaxReturn($jsons);
        }else if($type == 'dec'){ // 减少
            $ret = M('users')->where($map)->setDec('gold', $gold);
            if($ret){
                $jsons['errno'] = 0;
                $jsons['msg'] = '扣减成功';
            }else{
                $jsons['errno'] = 5;
                $jsons['msg'] = '扣减失败';
            }
            $this->ajaxReturn($jsons);
        }else if($type == 'inc'){ // 增加
            $ret = M('users')->where($map)->setInc('gold', $gold);
            if($ret){
                $jsons['errno'] = 0;
                $jsons['msg'] = '增加成功';
            }else{
                $jsons['errno'] = 6;
                $jsons['msg'] = '增加失败';
            }
            $this->ajaxReturn($jsons);
        }else{
            $jsons['errno'] = 7;
            $jsons['msg'] = '操作类型不正确';
            $this->ajaxReturn($jsons);
        }
    }

    // 清除群分享日志
    public function clearGroupLog()
    {
        $userid = I('userid','','string');  // 用户编号
        $type = I('type',2,'int');  // 1:普通分享 2：分享到群限制分享

        if($userid && $type) {
            $redis = REDIS('activity');
            $redis->select(1);

            $userKey = sprintf(self::QID_UID,$userid,$type,'*');  //用户主键分享到群
            $delKey = $redis->keys($userKey);
            $redis->del($delKey);
            // $userKey = sprintf(self::QID_UID,$userid,$type);  //用户主键分享到群
            // $redis->del($userKey);
        }

        $this->countLog('pwzwtwos',self::PWZW_PLAY,1);  // 记录玩游戏次数

        $jsons['errno'] = 0;
        $jsons['msg'] = '操作成功';
        $this->ajaxReturn($jsons);
    }

    // 向房间推送消息
    public function pushMsg()
    {
        $roomId = I('roomId','','string'); // 切记字符类型
        $state = I('state',1,'int'); // 1好友加入, 2开始游戏, 3放弃游戏, 4同步游戏界面
        $msg = I('msg','','string');
        $plus = I('plus','','string');
        $channel = I('channel','','string'); // 渠道

        $contents['channel'] = $channel;
        $contents['roomId'] = $roomId;
        $contents['state'] = $state;
        $contents['msg'] = $msg;
        $contents['plus'] = $plus;

        $sendMsg = $this->sendMsg($contents);
        $sendMsg = str_replace("\n",'',$sendMsg);

        $jsons['state'] = $sendMsg;
        $this->ajaxReturn($jsons);
    }

    // Socket发送数据
    private function sendMsg($contents)
    {
        // 建立socket连接到内部推送端口
        $client = stream_socket_client('tcp://127.0.0.1:5678', $errno, $errmsg, 1);
        // 推送的数据，包含uid字段，表示是给这个uid推送

        // 发送数据，注意5678端口是Text协议的端口，Text协议需要在数据末尾加上换行符
        fwrite($client, json_encode($contents)."\n");
        // 读取推送结果
        return fread($client, 8192);
    }

    // 记录游戏成绩
    public function addGameResult()
    {
        $userid = I('userid','','string');
        $score = I('score','','string');
        $nickname = I('nickname','','string');
        $avatar = I('avatar','','string');

        if(strlen($userid) == 30){
            $jsons['errno'] = 1;
            $jsons['msg'] = '游客不记录成绩';
            $this->ajaxReturn($jsons);
        }else if($userid == 'undefined' || $nickname == 'undefined' || $avatar == 'undefined'){
            $jsons['errno'] = 2;
            $jsons['msg'] = '字段不能为undefined';
            $this->ajaxReturn($jsons);
        }else if(!$userid){
            $jsons['errno'] = 3;
            $jsons['msg'] = '用户userid不能为空';
            $this->ajaxReturn($jsons);
        }else if(empty($score)){
            $jsons['errno'] = 4;
            $jsons['msg'] = '用户成绩不能为空';
            $this->ajaxReturn($jsons);
        }else{
            $map['userid'] = $userid;
            $data1['score'] = $score;
            $data1['update_time'] = date('Y-m-d H:i:s');

            $res = M('users')->field('score,id,nickname,avatar,userid')->where($map)->find();

            $redis = REDIS('activity');
            $redis->select(2);
            $hashKey = self::RANK_LIST; //排行榜列表
            $rank_list = $redis->hGetAll($hashKey);
            if($rank_list){
                $data = array('id'=>$res['id'],'s'=>$score,'userid'=>$res['userid'],'nickname'=>$res['nickname'],'avatar'=>$res['avatar']);

                $this->setRankList($hashKey,2,$data,$res['id'],'s',$score);// 记录缓存成绩
            }

            if($score > $res['score']) {
                M('users')->where($map)->save($data1);
            }

            $jsons['errno'] = 0;
            $jsons['msg'] = '添加成功';
            $this->ajaxReturn($jsons);
        }
    }

    // 用户登录游戏跟新数据
    public function upgrade() {
        $memory = memory_get_usage();
        $userid = I('userid','','string');
        $gold = I('gold',0,'string');  //金币
        $bullet_level = I('bullet_level',0,'int');  // 子弹等级
        $fire_level = I('fire_level',0,'int');  // 火力等级
        $game_time_level = I('game_time_level',0,'int'); //游戏金币掉落等级
        $offline_time_level = I('offline_time_level',0,'int'); // 离线领金币等级
        $diamonds = I('diamonds','0','string'); // 钻石

        if(!$userid){
            $jsons['errno'] = 2;
            $jsons['msg'] = '用户userid不能为空';
            $this->ajaxReturn($jsons);
        }
        //$data = array();
        $map['userid'] = $userid;
        $field = 'gold,diamonds,bullet_level,fire_level,game_time_level,offline_time_level,id,nickname';
        $userInfo = M('users')->field($field)->where($map)->find();

        $redis = REDIS('activity');
        $redis->select(1);
        $userKey = 'offline:user:'.$userid;
        $offline_time = $redis->get($userKey);

        if($bullet_level > $userInfo['bullet_level'] || $fire_level > $userInfo['fire_level'] || $game_time_level > $userInfo['game_time_level'] || $offline_time_level > $userInfo['offline_time_level'] || $gold != $userInfo['gold'] || $diamonds != $userInfo['diamonds'] || $offline_time > 0 ) {

            $data = array(
                'bullet_level' => $bullet_level,
                'fire_level'  => $fire_level,
                'game_time_level' => $game_time_level,
                'offline_time_level' => $offline_time_level
            );

            $data['gold'] = $gold;
            $data['diamonds'] = $diamonds;
            $where['id'] = $userInfo['id'];

            if(!empty($offline_time)) {
                $data['offline_time'] = array('exp',"offline_time + $offline_time");
            }

            $ret = M('users')->where($where)->save($data);

            if(!empty($data['offline_time'])) {
                $redis->del($userKey);
            }

            //$times = date("Y-m-d H:i:s");
            //$str = '用户编号:'.$userInfo['id'].'用户昵称:'.$userInfo['nickname'].'跟新时间:'.$times.'金币数:'.$gold.'钻石数:'.$diamonds.'子弹等级:'.$bullet_level.'火力等级:'.$fire_level.'掉落金币：'.$game_time_level.'领金币等级:'.$offline_time_level;

            //Log::write('upgrade:'.$str,'SUCCESS');

            $this->countLog('pwzwtwos',self::PWZW_UPGRADE,1);  // 升级成功次数
        }
        // 释放变量内存
        unset($userInfo);
        unset($data);
        unset($ret);
        unset($field);
        unset($offline_time);
        unset($gold);
        unset($fire_level);
        unset($game_time_level);
        unset($offline_time_level);
        unset($diamonds);

        $memory2 = memory_get_usage();
        log::write("跟新数据内存unset后：".$this->convert($memory2-$memory));

        $jsons['errno'] = 0;
        $jsons['msg'] = '操作成功';
        $this->ajaxReturn($jsons);
    }

    // 每日大礼包（存储）
    public function setGiftData(){

        $uid = isset($this->uid)?$this->uid:I('post.id','','string');  // 用户 openid
        $json = I('post.data'); // Json

        if(empty($uid) || empty($json)){
            $this->response(1, "参数不能为空！");
        }else{
            $goods=htmlspecialchars_decode($json);
            $goods_list=html_entity_decode($goods);
            $data['uid'] = $uid;
            $data['data'] = $goods_list;//转义后
            $data['create_time'] = date('Y-m-d H:i:s');
            $user = M('git')->where(array('uid'=>$uid))->find();

            if($user){
                $res = M('git')->where(array('uid'=>$uid))->save($data);
            }else{
                $res = M('git')->add($data);
            }
            if($res){
                $this->response(0, "ok");
            }else{
                $this->response(2, "大礼包存储失败");
            }

        }


    }

    // 每日大礼包（获取）
    public function getGiftData(){

        $uid = isset($this->uid)?$this->uid:I('post.id');  // 用户ID

        if(empty($uid)){
            $this->response(1, "参数不能为空！");
        }else{
            $data['uid'] = $uid;
            $info = M('git')->field('uid,data,create_time')->where($data)->find();
            if(empty($info)){
                $this->response(3, "没有数据");
            }
            $info['data'] = json_decode($info['data'],true);
            $this->response(0, "ok",$info);
        }
    }

    // 用户皮肤json（存储）
    public function setJsonData(){

        $uid = isset($this->uid)?$this->uid:I('post.id','','string');  // 用户id
        $json = I('post.data'); // Json

        if(empty($uid) && empty($json)){
            $this->response(1, "参数不能为空！");
        }else{
            $goods=htmlspecialchars_decode($json);
            $goods_list=html_entity_decode($goods);
            $data['id'] = $uid;
            $data['have_skin'] = $goods_list;//转义后
            $user = M('users')->where(array('id'=>$uid))->find();

            if($user){
                $res = M('users')->where(array('id'=>$uid))->save($data);
                if($res){
                    $this->response(0, "ok");
                }
            }else{
                $this->response(2, "用户不存在");
            }
        }
    }

    // 用户皮肤json（获取）
    public function getJsonData(){

        $uid = isset($this->uid)?$this->uid:I('post.id','','string');  // 用户id

        if(empty($uid)){
            $this->response(1, "参数不能为空！");
        }else{
            $data['id'] = $uid;
            $info = M('users')->field('id,have_skin as data')->where($data)->find();
            if(empty($info)){
                $this->response(3, "没有数据");
            }
            $info['data'] = json_decode($info['data'],true);
            $this->response(0, "ok",$info);
        }
    }

    // 邀请列表 当天邀请/永久
    public function hiringList() {
        //$uid = $this->uid;
        $uid = isset($this->uid)?$this->uid:I('post.id');// openid
        log::write("hiringList:".$uid,"ERROR");
        // 邀请类型 1:每日邀请 2：招募保安  3：招募会计 4：招募经理 5：招募总监  6:金币加速
        $post = I('post.type');  // type[2,3,4,5,6] json数组
        if(!empty($post)){
            if(is_array($post)){
                $type = $post;
            }else{
                $type = json_decode($post,true);
            }
        }else{
            $type=1;
        }

        $sort = I('post.sort'); //
        $dbname = self::DB_INVITELOG_NAME; // 邀请数据表 users_invite
        $dbname2 = self::DB_USER_NAME;  //  游戏用户数据表 users

        if($type !=99){
            if($sort ==1){
                $time = date('Y-m-d');// 今日邀请
            }else{
                $time = '';// 所有邀请
            }
        }

        $list = $this->commUserInvite_p2($uid,$type,$dbname,$dbname2,$time);// 邀请记录
        $info = array();
        if(!empty($list['userInfo'])) {
            // 按请求类型输出所属信息
            foreach( $list['userInfo'] as $k => $v) {
                $info[$v['type']][] = $v;//所有标识
            }
        }

        //$info = array('2'=>$guard,'3'=>$finance,'4'=>$manager,'5'=>$director,'6'=>$speed,'number'=>$list['number']);
        $num = $list['number'];
        $this->response(0, "ok",$info,$num);

    }

    // 邀请好友列表 关联
    public function hiringLists() {
        $uid = isset($this->uid)?$this->uid:I('post.id');
        log::write("hiringLists:".$uid,"ERROR");
        $array_id = array('uid'=>'userid','i_id'=>'invited_userid');// 对比Id
        $id = 'userid';// 根据Id
        $dbname = self::DB_INVITELOG_NAME; // 邀请数据表 pwtwo_game.users_invite
        $dbname2 = self::DB_USER_NAME;  //  游戏用户数据表 pwtwo_game.users

        $list = $this->commUserInvites($id,$array_id,$uid,$dbname,$dbname2);// 邀请记录

        $info =array();
        if(!empty($list['userInfo'])) {
            // 按请求类型输出所属信息
            foreach( $list['userInfo'] as $k => $v) {
                $info[] = $v;//所有标识
            }
        }

        $this->response(0, "ok",$info);

    }

    // 获取服务器当前时间
    public function getServerTime(){
        $time = time();
        $this->response(0, "ok",$time);
    }

    // 转发记录接口 转发次数人数记录
    public function forward(){
        $uid = isset($this->uid)?$this->uid:I('post.id');  // 用户ID
        $invite_uid = I('invite_uid','','int');
        $type = I('type','','int'); // 1:查询;2:添加;3:删除
        $type_table = 'pwtwo';   // redis表
        $this->getForward2($uid,$invite_uid,$type_table,$type);
    }

    public function get_uid() {
        $username= I('get.username');
        $map['nickname'] = array('like',$username.'%');;
        $username = M('users')->where($map)->find();
        var_export($username);
    }

    public function set_zadd(){
        $redis = REDIS('activity');
        $redis->select(2);
        $ret = M('users')->field('score as s,userid,nickname,avatar,id')->where('type=1')->order('s desc')->limit(200)->select();
        foreach($ret as $k=>$v) {
            $score = $v['score'];
            $res = $redis->zAdd('pwtwo',$score,json_encode($v));
        }


    }


    public function get_zadd(){
        $redis = REDIS('activity');
        $redis->select(2);
        /*$ret = M('users')->field('score as s,userid,nickname,avatar,id')->where('type=1')->order('s desc')->limit(200)->select();
        foreach($ret as $k=>$v) {
            $score = $v['score'];
            $res = $redis->zAdd('pwtwo',$score,json_encode($v));
        }*/

        $costList = $redis ->zrevRangeByScore('pwtwo',"+inf","-inf",['withscores' => false,"limit" =>[0,200]]);

        var_export($costList);
    }

    /**
     * 给出对应的排行榜
     * @param int $number 需要给出排行榜数目
     * @param bool $asc 排序顺序 true为按照高分为第0
     * @param bool $withscores 是否需要分数
     * @param callback $callback 用于处理排行榜的回调函数
     * @return [] 对应排行榜
     */
    public function getLeadboard($number, $key,$asc = true)
    {
        $redis = REDIS('activity');
        $redis->select(2);
        if ($asc) {
            $nowLeadboard =  $redis->zRevRange($key, 0, $number -1);//按照高分数顺序排行;
        } else {
            $nowLeadboard =  $redis->zRange($key, 0, $number -1);//按照低分数顺序排行;
        }

        return $nowLeadboard;
    }


    public function getLeadboards(){
        $res = $this->getLeadboard(200,'pwtwo',true);

        var_dump($res);
    }

    /**
     * 获取给定节点的排名
     * @param string $node 对应的节点的key名
     * @param string $asc 是否按照分数大小正序排名, true的情况下分数越大,排名越高
     * @return 节点排名,根据$asc排序,true的话,第一高分为0,false的话第一低分为0
     */
    public function getNodeRank()
    {
        $redis = REDIS('activity');
        $redis->select(2);
        $key ='pwtwo';
        $code = 's';
        $res = $redis->zRevRank($key,$code);
        var_dump($res);

    }

}
